﻿const express = require('express')
const TextToSVG = require('text-to-svg')
const multer = require('multer')
const router = express.Router()
const pathModel = require('path')
// 分解文字
const countLine = function({obj, SVG, options}) {
	let newArr = [], totalWidth = obj.width + 2;
	return Promise.all(Array.from(obj.arrList).map(function (text){
		let newStr = '', width = 0;
		text = text.split('')
		// console.log(text)
		return new Promise((resolve, reject) => {
			let len = text.length;
			// console.log(len)
			for (let i = 0; i <= len; i++) {
				let str = text[i]; 
				if (str == undefined) {
					newArr.push(newStr)
					return resolve(newArr)
				}
				let	box = SVG.getMetrics(str,options);
				width += box.width
//console.log(width, totalWidth)
				if (width <= totalWidth) {
					newStr += str
				} else {
					newArr.push(newStr)
					newStr = str
					width = box.width
				}
			}
		})
	}))
};
// 生成
const production = function({SVG, obj, options}) {
	
	let svg = '', maxX = 0, width = 0, height = 0, pathList = [];
	obj.arrList.forEach((item, i)=> {
		let box = SVG.getMetrics(item, options),
			path = SVG.getPath(item, options);
		if (obj.underline != 0) {
			path += `<line x1="${box.x}" x2="${box.width + box.x}" y1="${-box.descender/2}" y2="${-box.descender/2}" stroke="${obj.fill}" stroke-width="${Math.abs(box.height /box.descender)}" ></line>`
		}
		 //console.log(box)
		maxX = maxX < Math.abs(box.x) ? Math.abs(box.x) : maxX;
		pathList.push({path, y:obj.line * obj.size * i + box.ascender})
		width = width < box.width ? width = box.width : width;
		height += box.height
	})
	pathList.forEach(item => {
		svg += `<g transform='translate(${maxX},${ item.y})'>${item.path}</g>`
	})

	return {svg, width, height}
}


router.post('/textToPath', (req, res) => {
	//console.log(req.body)
	let obj = req.body || {
		family: '思源黑体-常规',
		width: 180,
		arrList: ['顺丰到付缩放'],
		size: 30,
		spacing: 0,
		line: 0,
		itailic: 0,
		bold: 0,
		underline: 0
	};
	//console.log(obj)
	if(obj == '') return res.send('传输为空')
    obj.itailic = obj.itailic == 1 ? 'translate(10, 0) skewX(-15)' : '';
	let	options = { // 文字属性设置
			fontSize: obj.size, 
			anchor: 'left',
			kerning: false,
			letterSpacing: obj.spacing,
			attributes: {
				transform: `${obj.itailic}`,
				'stroke-width': obj.bold,
				'stroke-linecap': 'round',
				'stroke-linejoin': 'round',
			}
		};
		
	let	SVG = TextToSVG.loadSync(`./font/${obj.family}.ttf`);// 字体设置
	//countLine({obj, SVG, options}).then(data => {
		//obj.arrList = data[0]
		// 返回的path字符串
		let result = production({SVG, obj, options})
		res.send(result)
	//})
})



const testproduction = function({SVG, obj, options}) {
	let svg = '', maxX = 0, width = 0, height = 0, pathList = [];
	obj.arrList.forEach((item, i)=> {
		let box = SVG.getMetrics(item, options),
			path = SVG.getPath(item, options);
		if (obj.underline != 0) {
			path += `<line x1="${box.x}" x2="${box.width + box.x}" y1="${-box.descender /2}" y2="${-box.descender/2}" stroke="${obj.fill}" stroke-width="${Math.abs(box.height /box.descender)}" ></line>`
		}
		 //console.log(box)
		maxX = maxX < Math.abs(box.x) ? Math.abs(box.x) : maxX;
		pathList.push({path, y:obj.line * obj.size * i + box.ascender})
		width = width < box.width ? width = box.width : width;
		height += box.height
	})
	pathList.forEach(item => {
		svg += `<g transform='translate(${maxX},${ item.y})'>${item.path}</g>`
	})
	return {svg, width, height}
}



router.get('/textTest', (req, res) => {
	let obj = {
		family: '思源黑体 Heavy',
		width: 180,
		arrList: ['刘','双击修改文字','修改','双击文字'],
		size: 30,
		spacing: 0,
		line: 1.2,
		itailic: 0,
		bold: 0,
		underline: 0,
		align: 'center'
	};
	obj.align = obj.align + ' baseline'
	console.log(pathModel.resolve('./font/' + obj.family + '.ttf'))
	let SVG = TextToSVG.loadSync('./font/' + obj.family + '.ttf');// 字体设置
	// console.log(obj)
	let	options = { // 文字属性设置
			fontSize: obj.size, 
			anchor: obj.align,
			letterSpacing: obj.spacing,
			attributes: {
				transform: obj.itailic == 1 ? 'translate(10, 0) skewX(-15)' : '',
				'stroke-width': obj.bold,
				'stroke-linecap': 'round',
				'stroke-linejoin': 'round',
			}
		};
	let result = testproduction({SVG, obj, options})
	let data = `<svg width="${result.width}" height="${result.height}" viewBox="0 0 ${result.width} ${result.height}">${result.svg}</svg>`
	res.send(data)
	
})
router.post('/textToPath/pro', (req, res) => {
	let obj = req.body || '';
	obj = typeof obj == 'string' ? JSON.parse(obj) : obj;
	//console.log(obj)
	if(obj == '') return res.send('传输为空')
	obj.align = 'baseline' + obj.align
	let	options = { // 文字属性设置
			fontSize: obj.size, 
			anchor: obj.align,
			letterSpacing: obj.spacing,
			attributes: {
				transform: obj.itailic == 1 ? 'translate(10, 0) skewX(-15)' : '',
				'stroke-width': obj.bold
			}
		};
		console.log(obj.family)
	let	SVG = TextToSVG.loadSync(`./font/${obj.family}.ttf`);// 字体设置

	let result = production({SVG, obj, options})
	res.send(result)
	
})




module.exports = router;